package com.za.plugin.transfer.func;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


// 把 regexp 转为 REGEXP_LIKE()

public class RegexpFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return sql.contains(" regexp ");
    }


    @Override
    public String transfer(String sql) {
        sql=sql.toLowerCase();
        if (sql.contains(" regexp ")) {
            // regexp 在最后面，就没有 ' ' 了
            sql = sql + " ";
            Pattern compile = Pattern.compile("\\s+([1-9a-zA-Z_?.,'\"]+)\\s+regexp\\s+([1-9a-zA-Z_?.,'\"]+)\\s+");
            Matcher matcher = compile.matcher(sql);
            if (matcher.find()) {
                int start = matcher.start();
                int end = matcher.end();
                // 'c' 表示大小写敏感，'i' 表示不敏感
                String s = " REGEXP_LIKE(" + matcher.group(1) + "," + matcher.group(2) + ",'c') ";
                sql = sql.substring(0, start) + s + sql.substring(end).trim();
                sql = sql.trim();
            }
        }
        return sql;
    }
}
